<template>
  <div class="content-layout-body">
    <base-search
      :title="t('keys.toBeApproved')"
      :schema="gettoBeApprovedSearchData()"
      :expand="true"
      :isShowSearch="selectionRowData.length"
      @search-submit="searchSubmit"
      @reset-submit="resetSubmit"
      v-permission="['home.approvalCenter.to-be-approved.see']"
    />
    <base-table
      ref="tableRefCom"
      v-loading="loading"
      border
      :selection="true"
      reserveSelection
      :row-style="{ cursor: 'pointer' }"
      row-key="id"
      rowKey="id"
      :columns="gettoBeApprovedList()"
      :data="tableData"
      :pagination="{
        currentPage: defaultParams.page,
        total: total,
        onSizeChange: handleSizeChange,
        onCurrentChange: handleCurrentChange
      }"
      @selection-change="handleSelectionChange"
      v-permission="['home.approvalCenter.to-be-approved.see']"
    >
      <template #btn>
        <el-button type="primary" @click="approvalClick('ok')">{{ t('keys.Batch_approval') }}</el-button>
        <el-button type="info" @click="approvalClick('no')">{{ t('keys.Batch_rejection') }}</el-button>
        <!-- <el-button type="info" @click="coModelClick">转交</el-button> -->
        <el-button type="info" link @click="initData">{{ t('keys.toBeApproved') }} ({{ approveCount }})</el-button>
      </template>
      <template #ticketCode="scope">
        <el-button type="info" link @click.stop="goToBeApprovedDetails(scope.row)">{{ scope.row.ticketCode }}</el-button>
      </template>
      <template #status="scope">
        {{ scope.row.enabledFlag ? t('keys.Published') : t('keys.draft') }}
      </template>
      <template #action="scope">
        <el-button type="info" link @click.stop="textareaModelClick('ok', scope.row)" v-permission="['home.approvalCenter.to-be-approved.edit']">{{
          t('keys.approval')
        }}</el-button>
        <el-button
          type="danger"
          link
          @click.stop="textareaModelClick('no', scope.row)"
          v-permission="['home.approvalCenter.to-be-approved.reject']"
          >{{ t('keys.reject') }}</el-button
        >
      </template>
    </base-table>
    <!-- 转交 -->
    <textarea-model
      ref="textareaModelChild"
      :autosize="{ minRows: 4, maxRows: 5 }"
      :textareaModelObj="textareaModelObj"
      :descriptionFalg="descriptionFalg"
      @textareaModel-submit="textareaModelSubmit"
    ></textarea-model>
    <!-- 拒绝 -->
    <co-model ref="coModelChild" :coModelObj="coModelObj" @coModel-submit="coModelSubmit"></co-model>
  </div>
</template>

<script setup>
import { ref, onActivated, reactive, nextTick, watch } from 'vue'
import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { ERR_OK } from 'config/statusCode'
import { getUserInfo } from 'utils/headerToken'
import { useBasicData } from './hooks/useBasicData'
import { gettoBeApprovedList } from './tableColumn'
import { gettoBeApprovedSearchData } from './hooks/useSearchData'

// import ZcbSearch from 'components/zcb-search'
// import BasicTable from 'components/table/basicTable.vue'
import textareaModel from './component/textareaModel.vue'
import coModel from './component/coModel.vue'

import {
  waitingApproveListApi,
  processApproveTaskPassApi,
  processApproveTaskRefuseApi,
  processApproveTasktRansferApi,
  getWaitingApproveCountApi
} from '@/api/personalCenter'
import { useI18n } from 'vue-i18n'
const { t } = useI18n() // 中英文

const store = useStore()
const router = useRouter()

const {
  tableRefCom,
  defaultParams,
  selectionRowData,
  tableData,
  loading,
  total,
  rowData,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  onRowClick,
  clearSelectionKeys,
  getList,
  searchSubmit,
  resetSubmit
} = useBasicData({
  listFun: waitingApproveListApi
})
// 每次都执行
onActivated(() => {
  initData()
})

const initData = async () => {
  setTimeout(async () => {
    await clearSelectionKeys()
    await getList()
    await getWaitingApproveCount()
  }, 1000)
}
const textareaModelObj = reactive({
  title: '',
  copywriting: '', // 文案
  copywritingBill: '' // span包裹的文案
})
const textareaNum = ref(0) // 0-批量批准 1-批量拒绝 2-行批准 3-行批准
const approvalActionList = ref([])
const textareaModelChild = ref(null)
const descriptionFalg = ref(true)
// 批量拒绝和批准
const approvalClick = (val) => {
  if (selectionRowData.value.length <= 0) {
    ElMessage.warning(t('keys.please_select_table_line'))
    return
  }
  descriptionFalg.value = true
  // 批准
  if (val == 'ok') {
    textareaModelObj.title = t('keys.approval')
    textareaModelObj.copywriting = t('keys.Approve_Process_Approval') + '?'
    textareaModelObj.label = t('keys.approve_comment')
    textareaNum.value = 0
    descriptionFalg.value = false
    // 拒绝
  } else if (val == 'no') {
    textareaModelObj.title = t('keys.reject')
    textareaModelObj.copywriting = t('keys.Reject_process_approval') + '?'
    textareaModelObj.label = t('keys.approve_comment')
    textareaNum.value = 1
  }
  approvalActionList.value = selectionRowData.value
  nextTick(() => {
    textareaModelChild.value.showModel()
  })
}
// 行批准拒绝
const textareaModelClick = (code, row) => {
  descriptionFalg.value = true
  let tit = `${row.ticketCode}${row?.ticketName ? '-' + row?.ticketName : ''}`
  //批准
  if (code == 'ok') {
    textareaModelObj.title = t('keys.approval')
    textareaModelObj.copywriting = `${t('keys.Approve_Process')}<span> ${tit} </span>${t('keys.is_it')}`
    textareaModelObj.label = t('keys.approve_comment')
    textareaNum.value = 2
    descriptionFalg.value = false
  } else {
    // 拒绝
    textareaModelObj.title = t('keys.reject')
    textareaModelObj.copywriting = `${t('keys.Reject_process')}<span> ${tit} </span>${t('keys.is_it')}`
    textareaModelObj.label = t('keys.approve_comment')
    textareaNum.value = 3
  }
  // operator 批准/驳回审批：缺少operator参数
  row.operator = getUserInfo().empId || '' // 操作人
  approvalActionList.value = [row]
  nextTick(() => {
    textareaModelChild.value.showModel()
  })
}
// 意见弹板返回的数据
const textareaModelSubmit = (res) => {
  // 0-批量批准 1-批量拒绝 2-行批准 3-行批准
  if (textareaNum.value == 0) {
    setApprovalOk(res)
  } else if (textareaNum.value == 1) {
    setApprovalNo(res)
  } else if (textareaNum.value == 2) {
    setApprovalOk(res)
  } else if (textareaNum.value == 3) {
    setApprovalNo(res)
  }
}
const setApprovalOk = async (val) => {
  let param = {
    approvalActionList: approvalActionList.value,
    comment: val.description
  }
  const { code, data } = await processApproveTaskPassApi(param) // 批准
  if (code === ERR_OK) {
    ElMessage.success(t('keys.approval') + t('keys.success'))
    initData()
  }
}
const setApprovalNo = async (val) => {
  let param = {
    approvalActionList: approvalActionList.value,
    comment: val.description
  }
  const { code, data } = await processApproveTaskRefuseApi(param) // 拒绝
  if (code === ERR_OK) {
    ElMessage.success(t('keys.reject') + t('keys.success'))
    initData()
  }
}
// 转交
const coModelChild = ref(null)
const coModelObj = reactive({
  title: '',
  copywriting: '', // 文案
  copywritingBill: '' // span包裹的文案
})
// const coModelClick = () => {
//   if (selectionRowData.value.length <= 0) {
//     ElMessage.warning('未进行选择，请勾选后进行操作')
//     return
//   }
//   coModelObj.title = '转交'
//   coModelObj.labelOne = '转交人'
//   coModelObj.labelTwo = '转交原因'
//   nextTick(() => {
//     coModelChild.value.showModel()
//   })
// }
const coModelSubmit = async (val) => {
  let seleList = []
  selectionRowData.value.forEach((item) => {
    seleList.push({
      processApproverTaskId: item.processApproverTaskId, // 流程审批任务id
      processInstanceId: item.processInstanceId, // 流程实例id
      processRuntimeId: item.processRuntimeId, // 流程运行节点id
      operator: getUserInfo().empId || '' // 操作人
    })
  })
  let param = {
    approvalActionList: seleList,
    comment: val.description,
    tenantId: localStorage.getItem('tenantId'),
    transferPerson: val.empId // 转交人
  }
  const { code, data } = await processApproveTasktRansferApi(param) // 拒绝
  if (code === ERR_OK) {
    ElMessage.success(t('keys.passed_on') + t('keys.success'))
    initData()
  }
}
const approveCount = ref(0)
// 获取待审批列表数
const getWaitingApproveCount = async () => {
  const { code, data } = await getWaitingApproveCountApi()
  if (code === ERR_OK) {
    const initStore = store.state.global.user
    initStore.toBeApprovedNum = data
    approveCount.value = data
    store.dispatch('global/setGlobalState', { user: initStore })
  }
}

const goToBeApprovedDetails = (row) => {
  router.push({
    name: 'toBeApprovedDetails',
    query: {
      instanceId: row.processInstanceId,
      ticketCode: row.ticketCode,
      ticketName: row.ticketName,
      processApproverTaskId: row.processApproverTaskId,
      sourceType: 'toBeApproved',
      source: 'preview'
    }
  })
}
</script>
